package com.omenkk.juc.ReentrantLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
@Slf4j
public class demo4 {
    static ReentrantLock lock=new ReentrantLock();
    static  Condition  waitCigaretteQueue=lock.newCondition();
    static  Condition  waitBreakfastQueue=lock.newCondition();
static boolean hasCigarette=false;
static boolean hasBreakfast=false;

    public static void main(String[] args) {
        new Thread(()->{
            try{
                //获取锁
                lock.lock();
                while(!hasCigarette){
                    try{
                        waitCigaretteQueue.await();
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
                log.debug("等到了烟");
            } finally {
                lock.unlock();
            }
        }).start();
        new Thread(()->{
            try{
                lock.lock();
                while(!hasBreakfast){
                    try{
                        waitBreakfastQueue.await();
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
                log.debug("获取了面包");
            }finally {
                lock.unlock();
            }
        }).start();

        //生产者线程
        new Thread(()->{

            lock.lock();
            try{
                log.debug("带来了烟");
                hasCigarette=true;
                waitCigaretteQueue.signalAll();
            }finally {
                lock.unlock();
            }
        }).start();

        new Thread(()->{

            lock.lock();
            try{
                log.debug("带来了面包");
                hasBreakfast=true;
                waitBreakfastQueue.signalAll();
            }finally {
                lock.unlock();
            }
        }).start();
    }

}
